var express = require('express');
const { formidable } = require('formidable');
var router = express.Router();


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/upload', (req, res) => {
  res.render('upload')
})

router.post('/upload', (req, res, next) => {

  const form = formidable({
    multiples: true,
    // 上传文件保存目录
    uploadDir: __dirname + '/../public/images',
    // 保持文件后缀
    keepExtensions: true
  });

  form.parse(req, (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    console.log(fields);
    console.log(files);
    // res.json({ fields, files });
    const url = `/images/${files.avatar[0].newFilename}`

    res.send(`成功 ${url}`)
  });

})

module.exports = router;
